﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.Web.AppCode;
using System.Data.SqlClient;

namespace Warehouse.Web.Management
{
    public partial class Products : BasePage
    {
        private List<DataAccess.Product> mProducts = null;
        private List<DataAccess.ProductSpecification> mProductSpecifications = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        protected override void ProcessAjaxRequest(HttpContext context, string action)
        {
            switch (action)
            {
                case "GetProducts":
                    {
                        WebUtil.WriteJsonResult(context, DataAccess.Product.GetProducts());
                    }
                    break;
                case "GetSpecification":
                    {
                        int specificationId = int.Parse(context.Request.QueryString["SpecificationID"]);
                        var specification = DataAccess.ProductSpecification.GetProductSpecification(specificationId);
                        if (specification != null)
                        {
                            if (string.Compare(context.Request.QueryString["Product"], "All", true) == 0)
                            {
                                WebUtil.WriteJsonResult(context, new
                                {
                                    Specification = specification,
                                    Products = DataAccess.Product.GetProducts()
                                });
                            }
                            else if (string.Compare(context.Request.QueryString["Product"], "Single", true) == 0)
                            {
                                WebUtil.WriteJsonResult(context, new
                                {
                                    Specification = specification,
                                    Product = DataAccess.Product.GetProduct(specification.ProductID)
                                });
                            }
                            else
                            {
                                WebUtil.WriteJsonResult(context, new
                                {
                                    Specification = specification
                                });
                            }
                        }
                        else
                        {
                            WebUtil.WriteJsonError(context, "该产品规格已经被删除");
                        }
                    }
                    break;
                case "AddCategory":
                    {
                        string CategoryName = context.Request.Form["CategoryName"];
                        if (!string.IsNullOrEmpty(CategoryName))
                        {
                            DataAccess.ProductCategory category = new Warehouse.DataAccess.ProductCategory()
                            {
                                Name = CategoryName
                            };
                            category.Save();
                            WebUtil.WriteJsonResult(context, null);
                        }
                        else
                        {
                            WebUtil.WriteJsonError(context, "分类名称不能为空");
                        }
                    }
                    break;
                case "ModifyCategory":
                    {
                        int categroyId = int.Parse(context.Request.Form["CategoryID"]);
                        string CategoryName = context.Request.Form["CategoryName"];
                        if (!string.IsNullOrEmpty(CategoryName))
                        {
                            DataAccess.ProductCategory category = Warehouse.DataAccess.ProductCategory.GetProductCategory(categroyId);
                            if (category != null)
                            {
                                category.Name = CategoryName;
                                category.Save();
                                WebUtil.WriteJsonResult(context, null);
                            }
                            else
                            {
                                WebUtil.WriteJsonError(context, "该分类已经被删除");
                            }
                        }
                        else
                        {
                            WebUtil.WriteJsonError(context, "分类名称不能为空");
                        }
                    }
                    break;
                case "DeleteCategory":
                    {
                        try
                        {
                            int categroyId = int.Parse(context.Request.Form["CategoryID"]);
                            DataAccess.ProductCategory category = DataAccess.ProductCategory.GetProductCategory(categroyId);
                            if (category != null)
                            {
                                category.Delete();
                            }
                            WebUtil.WriteJsonResult(context, null);
                        }
                        catch (SqlException ex)
                        {
                            if (ex.Number == 547)
                            {
                                WebUtil.WriteJsonError(context, "请先删除该分类下的所有产品");
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    break;
                case "DeleteSpecification":
                    {
                        try
                        {
                            int specificationID = int.Parse(context.Request.Form["ProductSpecificationID"]);
                            DataAccess.ProductSpecification specification = DataAccess.ProductSpecification.GetProductSpecification(specificationID);
                            if (specification != null)
                            {
                                specification.Delete();
                                if (DataAccess.ProductSpecification.GetProductSpecifications(specification.ProductID).Length == 0)
                                {
                                    DataAccess.Product p = DataAccess.Product.GetProduct(specification.ProductID);
                                    p.Delete();
                                }
                            }
                            WebUtil.WriteJsonResult(context, null);
                        }
                        catch (SqlException ex)
                        {
                            if (ex.Number == 547)
                            {
                                WebUtil.WriteJsonError(context, "该产品有出（入）库记录，不能删除");
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    break;
                case "DeleteProduct":
                    {
                        try
                        {
                            int productID = int.Parse(Request.Form["ProductID"]);
                            DataAccess.Product product = DataAccess.Product.GetProduct(productID);
                            if (product != null)
                            {
                                product.Delete();
                            }
                            WebUtil.WriteJsonResult(context, null);
                        }
                        catch (SqlException ex)
                        {
                            if (ex.Number == 547)
                            {
                                WebUtil.WriteJsonError(context, "删除失败，请刷新页面后重试\n错误：产品规格不为空");
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    break;
                case "AddProduct":
                    {
                        string ProductName = context.Request.Form["ProductName"].Trim();
                        string ProductSerialNumber = context.Request.Form["ProductSerialNumber"];
                        string ProductModel = context.Request.Form["ProductModel"];
                        string ProductGrade = context.Request.Form["ProductGrade"];
                        string ProductDescription = context.Request.Form["ProductDescription"];
                        string ProductCode = context.Request.Form["ProductCode"];
                        int ProductCategoryID = int.Parse(context.Request.Form["ProductCategoryID"]);
                        string Specification = context.Request.Form["Specification"];
                        string PackagingSpecification = context.Request.Form["PackagingSpecification"];
                        string Unit = context.Request.Form["Unit"];
                        double DeliveryPrice = double.Parse(context.Request.Form["PurchasePrice"] ?? "0");
                        double SellingPrice = double.Parse(context.Request.Form["SalePrice"] ?? "0");
                        if (string.IsNullOrEmpty(ProductName))
                        {
                            WebUtil.WriteJsonError(context, "产品名称不能为空");
                            return;
                        }
                        if (string.IsNullOrEmpty(Specification))
                        {
                            WebUtil.WriteJsonError(context, "产品规格不能为空");
                            return;
                        }
                        if (DeliveryPrice < 0)
                        {
                            WebUtil.WriteJsonError(context, "提货价不能小于0");
                            return;
                        }
                        if (SellingPrice < 0)
                        {
                            WebUtil.WriteJsonError(context, "经销价不能小于0");
                            return;
                        }
                        var product = DataAccess.Product.GetProduct(ProductName, ProductModel, ProductGrade);
                        if (product == null)
                        {
                            product = new Warehouse.DataAccess.Product();
                        }
                        product.Name = ProductName;
                        product.SerialNumber = ProductSerialNumber;
                        product.Model = ProductModel;
                        product.Grade = ProductGrade;
                        product.Description = ProductDescription;
                        product.Code = ProductCode;
                        product.CategoryID = ProductCategoryID;

                        product.Save();

                        var s = new DataAccess.ProductSpecification()
                        {
                            ProductID = product.ID,
                            Specification = Specification,
                            PackagingSpecification = PackagingSpecification,
                            Unit = Unit,
                            PurchasePrice = DeliveryPrice,
                            SalePrice = SellingPrice
                        };
                        s.Save();

                        WebUtil.WriteJsonResult(context, null);
                    }
                    break;
                case "SaveSpecification":
                    {
                        int ProductID = int.Parse(context.Request.Form["ProductID"]);
                        string ProductName = context.Request.Form["ProductName"].Trim();
                        string ProductSerialNumber = context.Request.Form["ProductSerialNumber"];
                        string ProductModel = context.Request.Form["ProductModel"];
                        string ProductGrade = context.Request.Form["ProductGrade"];
                        string ProductDescription = context.Request.Form["ProductDescription"];
                        string ProductCode = context.Request.Form["ProductCode"];
                        int ProductCategoryID = int.Parse(context.Request.Form["ProductCategoryID"]);
                        int SpecificationID = int.Parse(context.Request.Form["SpecificationID"]);
                        string Specification = context.Request.Form["Specification"];
                        string PackagingSpecification = context.Request.Form["PackagingSpecification"];
                        string Unit = context.Request.Form["Unit"];
                        double DeliveryPrice = double.Parse(context.Request.Form["PurchasePrice"] ?? "0");
                        double SellingPrice = double.Parse(context.Request.Form["SalePrice"] ?? "0");
                        if (string.IsNullOrEmpty(ProductName))
                        {
                            WebUtil.WriteJsonError(context, "产品名称不能为空");
                            return;
                        }
                        if (string.IsNullOrEmpty(Specification))
                        {
                            WebUtil.WriteJsonError(context, "产品规格不能为空");
                            return;
                        }
                        if (DeliveryPrice < 0)
                        {
                            WebUtil.WriteJsonError(context, "提货价不能小于0");
                            return;
                        }
                        if (SellingPrice < 0)
                        {
                            WebUtil.WriteJsonError(context, "经销价不能小于0");
                            return;
                        }
                        var product = DataAccess.Product.GetProduct(ProductID);
                        if (product == null)
                        {
                            WebUtil.WriteJsonError(context, "产品已被删除");
                            return;
                        }
                        product.Name = ProductName;
                        product.SerialNumber = ProductSerialNumber;
                        product.Model = ProductModel;
                        product.Grade = ProductGrade;
                        product.Description = ProductDescription;
                        product.Code = ProductCode;
                        product.CategoryID = ProductCategoryID;


                        DataAccess.ProductSpecification s = DataAccess.ProductSpecification.GetProductSpecification(SpecificationID);
                        if (s == null)
                        {
                            WebUtil.WriteJsonError(context, "规格已被删除");
                            return;
                        }
                        s.Specification = Specification;
                        s.PackagingSpecification = PackagingSpecification;
                        s.Unit = Unit;
                        s.PurchasePrice = DeliveryPrice;
                        s.SalePrice = SellingPrice;

                        product.Save();
                        s.Save();

                        WebUtil.WriteJsonResult(context, null);
                    }
                    break;
                default:
                    base.ProcessAjaxRequest(context, action);
                    break;
            }
        }

        void LoadData()
        {
            mProducts = new List<Warehouse.DataAccess.Product>(DataAccess.Product.GetProducts());
            mProductSpecifications = new List<Warehouse.DataAccess.ProductSpecification>(DataAccess.ProductSpecification.GetProductSpecifications());

            this.rptCategories.DataSource = DataAccess.ProductCategory.GetProductCategories();
            this.rptCategories.DataBind();
        }

        protected void rptCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item == null)
                return;
            DataAccess.ProductCategory category = e.Item.DataItem as DataAccess.ProductCategory;
            Repeater rptProducts = e.Item.FindControl("rptProducts") as Repeater;
            if (category != null && rptProducts != null)
            {
                List<object> list = new List<object>();

                foreach (var group in mProducts.Where(p => p.CategoryID == category.ID).GroupBy(arg => arg.SerialNumber).OrderBy(arg => arg.Key))
                {
                    int _ProductSpecificatoinCount = group.Sum(p => Math.Max(1, mProductSpecifications.Count(arg => arg.ProductID == p.ID)));
                    bool firstProduct = true;
                    foreach (var p in group)
                    {
                        DataAccess.ProductSpecification[] _Specifications = mProductSpecifications.Where(arg => arg.ProductID == p.ID).ToArray();
                        int _SpecificatoinCount = _Specifications.Length;
                        bool firstSpecification = true;
                        foreach (var s in _Specifications)
                        {
                            list.Add(new
                            {
                                FirstProduct = firstProduct,
                                FirstSpecification = firstSpecification,
                                ProductSpecificatoinCount = _ProductSpecificatoinCount,
                                SpecificatoinCount = _SpecificatoinCount,
                                Product = p,
                                Specification = s,
                            });
                            firstSpecification = false;
                            firstProduct = false;
                        }
                        if (firstSpecification)//没有添加任何规格
                        {
                            list.Add(new
                            {
                                FirstProduct = firstProduct,
                                FirstSpecification = firstSpecification,
                                ProductSpecificatoinCount = _ProductSpecificatoinCount,
                                SpecificatoinCount = _SpecificatoinCount,
                                Product = p,
                                Specification = DataAccess.ProductSpecification.Empty
                            });
                        }
                        firstProduct = false;
                    }
                }

                rptProducts.DataSource = list;
                rptProducts.DataBind();
            }
        }
    }
}
